package com.gexiaobao.pigeon.ui.fragment.mine.tools

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.view.View
import android.widget.EditText
import cn.qqtheme.framework.picker.DatePicker
import cn.qqtheme.framework.picker.DateTimePicker
import cn.qqtheme.framework.picker.TimePicker
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentCalculateBinding
import com.gexiaobao.pigeon.viewmodel.MinuteSpeedViewModel
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 9:44
 * @Describe    : 分速计算-计算
 */
class FragmentCalculate : BaseFragment<MinuteSpeedViewModel, FragmentCalculateBinding>(){

    var speedStart = 0L
    var speedEnd = 0L
    var calStart = 0L

    private var timePickerSpeedStart: DateTimePicker? = null
    private var timePickerSpeedEnd: DateTimePicker? = null
    private var timePickerCalStart: DateTimePicker? = null

    override fun initView(savedInstanceState: Bundle?) {
        timeCheck()

        val ss = SpannableString("尚未计算结果")
        val ass = AbsoluteSizeSpan(20, true)
        ss.setSpan(ass, 0, ss.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        mDatabind.toolsCalSpeedCommitTv.hint = ss
        mDatabind.tToolsCalTimeCommitTv.hint = ss

        mDatabind.toolsCalDistance.setOnFocusChangeListener { v, hasFocus ->
            hintSet(v, hasFocus)
        }
        mDatabind.tToolsCalSpeedTv.setOnFocusChangeListener { v, hasFocus ->
            hintSet(v, hasFocus)
        }
        mDatabind.tToolsCalDistance.setOnFocusChangeListener { v, hasFocus ->
            hintSet(v, hasFocus)
        }
    }

    private fun hintSet(v: View?, hasFocus: Boolean) {
        val editText = v as EditText
        var hint = ""
        if (hasFocus) {
            hint = editText.hint.toString()
            editText.tag = hint
            editText.hint = ""
        } else {
            hint = editText.tag.toString()
            editText.hint = hint
        }
    }

    @SuppressLint("SetTextI18n")
    private fun timeCheck() {
        timePickerSpeedStart = DateTimePicker(activity, DatePicker.YEAR_MONTH_DAY, TimePicker.HOUR_24)
        val params = timePickerSpeedStart!!.window.attributes
        params.width = requireActivity().windowManager.defaultDisplay.width
        timePickerSpeedStart!!.setTitleTextColor(Color.BLACK)
        timePickerSpeedStart!!.setTitleTextSize(18)
        timePickerSpeedStart!!.setSubmitText(getString(R.string.sure))
        timePickerSpeedStart!!.setSubmitTextSize(17)
        timePickerSpeedStart!!.setSubmitTextColor(resources.getColor(R.color.bg_light_bllue))//确定按钮文字颜色
        timePickerSpeedStart!!.setCancelText(getString(R.string.cancel))
        timePickerSpeedStart!!.setCancelTextSize(17)
        timePickerSpeedStart!!.setCancelTextColor(resources.getColor(R.color.bg_light_bllue))//取消按钮文字颜色
        timePickerSpeedStart!!.setTextSize(18)
        timePickerSpeedStart!!.setLineSpaceMultiplier(3.0F)
        timePickerSpeedStart!!.setDateRangeStart(
            Constant.TIME_PICKER_START_YEAR,
            Constant.TIME_PICKER_START_MONTH,
            Constant.TIME_PICKER_START_DAY
        )
        timePickerSpeedStart!!.setDateRangeEnd(
            Constant.TIME_PICKER_END_YEAR,
            Constant.TIME_PICKER_END_MONTH,
            Constant.TIME_PICKER_END_DAY
        )
        timePickerSpeedStart!!.setOnDateTimePickListener(object : DateTimePicker.OnYearMonthDayTimePickListener {
            override fun onDateTimePicked(year: String, month: String, day: String, hour: String, minute: String) {
                speedStart = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("$year-$month-$day $hour:$minute:00")!!.time
                mDatabind.toolsCalStartTimeTv.text = "${year}-${month}-${day} $hour:$minute"
            }
        })

        timePickerSpeedEnd = DateTimePicker(activity, DatePicker.YEAR_MONTH_DAY, TimePicker.HOUR_24)
        val paramsEnd = timePickerSpeedEnd!!.window.attributes
        paramsEnd.width = requireActivity().windowManager.defaultDisplay.width
        timePickerSpeedEnd!!.setTitleTextColor(Color.BLACK)
        timePickerSpeedEnd!!.setTitleTextSize(18)
        timePickerSpeedEnd!!.setSubmitText(getString(R.string.sure))
        timePickerSpeedEnd!!.setSubmitTextSize(17)
        timePickerSpeedEnd!!.setSubmitTextColor(resources.getColor(R.color.bg_light_bllue))//确定按钮文字颜色
        timePickerSpeedEnd!!.setCancelText(getString(R.string.cancel))
        timePickerSpeedEnd!!.setCancelTextSize(17)
        timePickerSpeedEnd!!.setCancelTextColor(resources.getColor(R.color.bg_light_bllue))//取消按钮文字颜色
        timePickerSpeedEnd!!.setTextSize(18)
        timePickerSpeedEnd!!.setLineSpaceMultiplier(3.0F)
        timePickerSpeedEnd!!.setDateRangeStart(
            Constant.TIME_PICKER_START_YEAR,
            Constant.TIME_PICKER_START_MONTH,
            Constant.TIME_PICKER_START_DAY
        )
        timePickerSpeedEnd!!.setDateRangeEnd(
            Constant.TIME_PICKER_END_YEAR,
            Constant.TIME_PICKER_END_MONTH,
            Constant.TIME_PICKER_END_DAY
        )

        timePickerSpeedEnd!!.setOnDateTimePickListener(object : DateTimePicker.OnYearMonthDayTimePickListener {
            override fun onDateTimePicked(year: String, month: String, day: String, hour: String, minute: String) {
                speedEnd = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("$year-$month-$day $hour:$minute:00")!!.time
                mDatabind.toolsCalEndTimeTv.text = "${year}-${month}-${day} $hour:$minute"
            }
        })

        timePickerCalStart = DateTimePicker(activity, DatePicker.YEAR_MONTH_DAY, TimePicker.HOUR_24)
        val paramsCalStart = timePickerCalStart!!.window.attributes
        paramsCalStart.width = requireActivity().windowManager.defaultDisplay.width
        timePickerCalStart!!.setTitleTextColor(Color.BLACK)
        timePickerCalStart!!.setTitleTextSize(18)
        timePickerCalStart!!.setSubmitText(getString(R.string.sure))
        timePickerCalStart!!.setSubmitTextSize(17)
        timePickerCalStart!!.setSubmitTextColor(resources.getColor(R.color.bg_light_bllue))//确定按钮文字颜色
        timePickerCalStart!!.setCancelText(getString(R.string.cancel))
        timePickerCalStart!!.setCancelTextSize(17)
        timePickerCalStart!!.setCancelTextColor(resources.getColor(R.color.bg_light_bllue))//取消按钮文字颜色
        timePickerCalStart!!.setTextSize(18)
        timePickerCalStart!!.setLineSpaceMultiplier(3.0F)
        timePickerCalStart!!.setDateRangeStart(
            Constant.TIME_PICKER_START_YEAR,
            Constant.TIME_PICKER_START_MONTH,
            Constant.TIME_PICKER_START_DAY
        )
        timePickerCalStart!!.setDateRangeEnd(
            Constant.TIME_PICKER_END_YEAR,
            Constant.TIME_PICKER_END_MONTH,
            Constant.TIME_PICKER_END_DAY
        )

        timePickerCalStart!!.setOnDateTimePickListener(object : DateTimePicker.OnYearMonthDayTimePickListener {
            override fun onDateTimePicked(year: String, month: String, day: String, hour: String, minute: String) {
                calStart = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("$year-$month-$day $hour:$minute:00")!!.time
                mDatabind.tToolsCalStartTimeTv.text = "${year}-${month}-${day} $hour:$minute"
            }
        })
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.toolsCalStartTime, mDatabind.toolsCalEndTime, mDatabind.tToolsCalStartTime, mDatabind.toolsCalSpeedCommit,
            mDatabind.tToolsCalTimeCommit
        ) {
            when (it) {
                mDatabind.toolsCalStartTime -> {
                    checkStartTime()
                }
                mDatabind.toolsCalEndTime -> {
                    checkEndTime()
                }
                mDatabind.tToolsCalStartTime -> {
                    checkCalStartTime()
                }
                mDatabind.toolsCalSpeedCommit -> {
                    speedCommit()
                }
                mDatabind.tToolsCalTimeCommit -> {
                    timeCommit()
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun timeCommit() {
        clearFocus()
        if (calStart == 0L) {
            showMessage("请选择放飞时间")
            return
        }
        if (TextUtils.isEmpty(mDatabind.tToolsCalSpeedTv.text)) {
            showMessage("请输入预估分速")
            return
        }
        if (mDatabind.tToolsCalSpeedTv.text.toString().toDouble() == 0.0) {
            showMessage("预估分速不能为0")
            return
        }
        if (TextUtils.isEmpty(mDatabind.tToolsCalDistance.text)) {
            showMessage("请输入空距")
            return
        }

        if (mDatabind.tToolsCalDistance.text.toString().toDouble() == 0.0) {
            showMessage("空距不能为0")
            return
        }

        if (mDatabind.tToolsCalDistance.text.toString().toDouble() > 10000.0) {
            showMessage("空距不能大于10000KM")
            return
        }
        if (mDatabind.tToolsCalSpeedTv.text.toString().toDouble() > 3000.0) {
            showMessage("分速不能大于3000米/分")
            return
        }

        val m = mDatabind.tToolsCalDistance.text.toString().toDouble() * 1000
        val speed = mDatabind.tToolsCalSpeedTv.text.toString().toDouble()
        val min = m / speed
        val ms = min * 60 * 1000
        val date = Date()

        val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("${mDatabind.tToolsCalStartTimeTv.text}:00")?.time
        date.time = time!! + ms.toLong()
        mDatabind.tToolsCalTimeCommitTv.text = "归巢时间:" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "\n" +
                "飞行时长:" + Util.formatDateTime(ms.toLong() / 1000)
    }

    @SuppressLint("SetTextI18n")
    private fun speedCommit() {
        clearFocus()
        if (speedStart == 0L) {
            showMessage("请选择放飞时间")
            return
        }
        if (speedEnd == 0L) {
            showMessage("请选择归巢时间")
            return
        }
        if (speedEnd - speedStart <= 0) {
            showMessage("归巢时间必须大于放飞时间")
            return
        }
        if (TextUtils.isEmpty(mDatabind.toolsCalDistance.text)) {
            showMessage("请输入空距")
            return
        }

        val km = mDatabind.toolsCalDistance.text.toString().toDouble()
        if (km <= 0.0) {
            showMessage("空距不能为0")
            return
        }
        if (km > 10000.0) {
            showMessage("空距不能大于10000KM")
            return
        }
        val min = (speedEnd - speedStart) / (60 * 1000)
        val speed = km * 1000 / min
        mDatabind.toolsCalSpeedCommitTv.text = String.format("%.4f", speed) + "米/分"
    }

    private fun checkCalStartTime() {
        clearFocus()
        if (TextUtils.isEmpty(mDatabind.tToolsCalStartTimeTv.text)) {
            val calendar = Calendar.getInstance()
            calendar.time = Date()
            val year = calendar.get(Calendar.YEAR)
            val month = calendar.get(Calendar.MONTH) + 1
            val day = calendar.get(Calendar.DATE)
            val hour = calendar.get(Calendar.HOUR_OF_DAY)
            val minute = calendar.get(Calendar.MINUTE)
            timePickerCalStart?.setSelectedItem(year, month, day, hour, minute)
        }
        timePickerCalStart?.show()
    }

    private fun checkEndTime() {
        clearFocus()
        if (TextUtils.isEmpty(mDatabind.toolsCalEndTimeTv.text)) {
            val calendar = Calendar.getInstance()
            calendar.time = Date()
            val year = calendar.get(Calendar.YEAR)
            val month = calendar.get(Calendar.MONTH) + 1
            val day = calendar.get(Calendar.DATE)
            val hour = calendar.get(Calendar.HOUR_OF_DAY)
            val minute = calendar.get(Calendar.MINUTE)
            timePickerSpeedEnd?.setSelectedItem(year, month, day, hour, minute)
        }
        timePickerSpeedEnd?.show()
    }

    private fun checkStartTime() {
        clearFocus()
        if (TextUtils.isEmpty(mDatabind.toolsCalStartTimeTv.text)) {
            val calendar = Calendar.getInstance()
            calendar.time = Date()
            val year = calendar.get(Calendar.YEAR)
            val month = calendar.get(Calendar.MONTH) + 1
            val day = calendar.get(Calendar.DATE)
            val hour = calendar.get(Calendar.HOUR_OF_DAY)
            val minute = calendar.get(Calendar.MINUTE)
            timePickerSpeedStart?.setSelectedItem(year, month, day, hour, minute)
        }
        timePickerSpeedStart?.show()
    }

    private fun clearFocus() {
        mDatabind.toolsCalLl.isFocusable = true
        mDatabind.toolsCalLl.isFocusableInTouchMode = true
        mDatabind.toolsCalLl.requestFocus()
    }

    companion object {
        fun newInstance(): FragmentCalculate {
            return FragmentCalculate()
        }
    }
}